<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px" size="small">
      <el-form-item label="价格名称" prop="priceName">
        <el-input v-model="dataForm.priceName" placeholder="价格名称"></el-input>
      </el-form-item>
       <el-form-item label="价格(元)" prop="price">
        <el-input v-model="dataForm.price" placeholder="价格" type="number"></el-input>
      </el-form-item>
      <el-row  :gutter="20">
        <el-col :span="12">
          <el-form-item label="能源类型" prop="energyType">
            <el-select v-model="dataForm.energyType"  style="width: 100%;" placeholder="请选择"  @change="changeMeter">
              <el-option
                v-for="(item, index) in meterTypeList" :key="index"
                :label="item.paramValue"
                :value="item.paramKey">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="采集类型" prop="collectType">
            <el-select v-model="dataForm.collectType"  style="width: 100%;" placeholder="请选择"  >
              <el-option
                v-for="(item, index) in collectTypeList" :key="index"
                :label="item.collectName"
                :value="item.collectType">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="生效时间" prop="effectTime">
            <el-date-picker v-model="dataForm.effectTime" type="datetime"  style="width: 100%;" placeholder="请选择生效时间" default-time="00:00:00"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="过期时间" prop="expireTime">
            <el-date-picker v-model="dataForm.expireTime" type="datetime"  style="width: 100%;" placeholder="请选择过期时间" default-time="23:59:59"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-table style="width: 100%" :data="dateDataList" border  height="200" size="mini">
          <el-table-column label="开始时间" align="left" prop="startVal">
            <template slot-scope="scope">
              <el-time-select v-model="scope.row.startVal" size="mini" :picker-options="dataTimeOption"  style="width: 100%;" placeholder="请选择开始时间" :clearable=false> </el-time-select>
            </template>
          </el-table-column>
          <el-table-column label="结束时间" align="left" prop="endVal">
            <template slot-scope="scope">
              <el-time-select v-model="scope.row.endVal" size="mini" :picker-options="Object.assign({minTime:scope.row.startVal},dataTimeOption)"  style="width: 100%;" :clearable=false placeholder="请选择结束时间"> </el-time-select>
            </template>
          </el-table-column>
          <el-table-column align="right" width="70">
            <template slot="header">
               <el-button size="mini" icon="el-icon-plus" type="primary" @click="addDataList()"></el-button>
            </template>
            <template slot-scope="scope">
              <el-button size="mini" type="danger" icon="el-icon-minus" @click="handleDelete(scope.$index, scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false" size="small">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" size="small">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import * as Util from "@/utils";
  export default {
    data () {
      return {
        meterTypeList:[],
        collectTypeList:[],
        visible: false,
        dataForm: {
          priceName:'',
          priceId: 0,
          energyType: '',
          collectType: '',
          price: '',
          startVal: '',
          endVal: '',
          effectTime: '',
          expireTime: ''
        },
        dataRule: {
          priceName: [
            { required: true, message: '价格名称不能为空', trigger: 'blur' }
          ],
          energyType: [
            { required: true, message: '能源类型不能为空', trigger: 'blur' }
          ],
          collectType: [
            { required: true, message: '采集类型不能为空', trigger: 'blur' }
          ],
          price: [
            { required: true, message: '价格不能为空', trigger: 'blur' }
          ],
          startVal: [
            { required: true, message: '开始时间不能为空', trigger: 'blur' }
          ],
          endVal: [
            { required: true, message: '结束时间不能为空', trigger: 'blur' }
          ],
          effectTime: [
            { required: true, message: '生效时间不能为空', trigger: 'blur' }
          ],
          expireTime: [
            { required: true, message: '过期时间不能为空', trigger: 'blur' }
          ]
        },
        dateDataList:[],
        dataTimeOption:{
          start: '00:00',
          step: '01:00',
          end: '24:00'
        }
      }
    },
    methods: {
      addDataList(){
        this.dateDataList.push({
          startVal:'00:00',
          endVal:'00:00',
        });
      },
      handleDelete(index,row){
        this.dateDataList.splice(index,1);
      },
      init (id,meterTypeList) {
        this.dateDataList=[]
        this.meterTypeList = meterTypeList
        this.dataForm.priceId = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.priceId) {
            this.$api.okhttp({
              url: this.$http.adornUrl(`/ecs/ecsprice/info/${this.dataForm.priceId}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then((data) => {
              if (data && data.code === 0) {
                this.dataForm.priceName = data.ecsprice.priceName
                this.dataForm.energyType = data.ecsprice.energyType
                this.dataForm.collectType = data.ecsprice.collectType
                this.dataForm.price = data.ecsprice.price
                // this.dataForm.startVal = new Date('2020-05-01 '+data.ecsprice.startVal)
                // this.dataForm.endVal = new Date('2020-05-01 '+data.ecsprice.endVal)
                this.dataForm.effectTime = new Date(data.ecsprice.effectTime)
                this.dataForm.expireTime = new Date(data.ecsprice.expireTime)
                this.dateDataList = data.timeRange
                this.changeMeter()
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if(this.dataForm.startVal>this.dataForm.endVal){
              this.$message.error("开始时间不能大于结束时间")
              return ;
            }
            if(this.dataForm.effectTime>this.dataForm.expireTime){
              this.$message.error("生效时间不能大于过期时间")
              return ;
            }
            if( this.dateDataList.length ===0){
              this.$message.error("开始时间和结束时间不能为空")
              return ;
            }
            this.$api.okhttp({
              url: this.$http.adornUrl(`/ecs/ecsprice/${!this.dataForm.priceId ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'priceId': this.dataForm.priceId || undefined,
                'priceName': this.dataForm.priceName,
                'energyType': this.dataForm.energyType,
                'collectType': this.dataForm.collectType,
                'price': this.dataForm.price,
                // 'startVal': this.dataForm.startVal.format('hh:mm:ss'),
                // 'endVal': this.dataForm.endVal.format('hh:mm:ss'),
                'effectTime': Util.dateFormat('YYYY-mm-dd HH:MM:SS',this.dataForm.effectTime),
                'expireTime': Util.dateFormat('YYYY-mm-dd HH:MM:SS',this.dataForm.expireTime),
                'timeRange':this.dateDataList,
                "customerId":this.$util.cookies.get('customer_id')
              })
            }).then((data) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      /**
       * 获取参数枚举
       */
      queryStatic(type,paramValue,callback) {
        let params = {
          'code': type ,
          "customerId":this.$util.cookies.get('customer_id')
        }
        if(paramValue){
          Object.assign(params,{...paramValue});
        }
        this.$api.okhttp({
          url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
          method: 'get',
          params: this.$http.adornParams(params)
        }).then((data) => {
          if(callback){
            callback(data);
          }
        });
      },
      changeMeter(){
        let params = {
          'meterType':this.dataForm.energyType,
          'state': '1' ,
          "customerId":this.$util.cookies.get('customer_id'),
          'page': 1,
          'limit': 10000,
        }
        this.$api.okhttp({
          url: this.$http.adornUrl('/ecs/ecscollectitem/list'),
          method: 'get',
          params: this.$http.adornParams(params)
        }).then((data) => {
          if (data && data.code === 0) {
          this.collectTypeList = data.page.list
        } else {
          this.collectTypeList = []
        }
      });

      }


    }
  }
</script>
